<template>
  <div class="login_box">
    <div class="login-container">
      <div class="login-version" v-if="sysConfig && sysConfig.sysVersion">
        <p class="login-version-text">{{ sysConfig.sysVersion }}</p>
      </div>
      <div class="login-left">
        <img class="login-banner" src="@/assets/images/blend.png" alt="" />
        <div class="login-left-txt" v-if="showTxt">
          <!-- 在线自动化，可视化系统开发，零代码实现80%的基础功能 -->
          <p class="title1">
            <!-- 在线自动化，可视化系统开发，零代码实现80%的基础功能 -->
          </p>
        </div>
      </div>
      <div class="login-content">
        <div class="login-form">
          <!-- <el-image
          class="login-logo"
          :src="define.comUrl + sysConfig.loginIcon"
          v-if="sysConfig && sysConfig.loginIcon"
        >
          <template slot="error">
            <img
              class="login-logo"
              src="@/assets/images/login_logo.png"
              alt=""
            />
          </template>
        </el-image>
        <img
          class="login-logo"
          src="@/assets/images/login_logo.png"
          alt=""
          v-else
        /> -->
          <h1 style="text-align: center">{{ pathTitle + "数字化管理平台" }}</h1>
          <div class="login-tab" :class="'active' + active">
            <a
              class="item"
              :class="{ active: active == 1 }"
              @click="active = 1"
              >{{ $t("login.title") }}</a
            >
            <a class="item" :class="{ active: active == 2 }" @click="active = 1"
              >&nbsp;</a
            >
          </div>
          <el-form
            v-show="active == 1"
            ref="loginForm"
            :model="loginForm"
            :rules="loginRules"
            autocomplete="on"
            label-position="left"
          >
            <el-form-item prop="account" style="margin-bottom: 20px">
              <el-input
                ref="account"
                v-model="loginForm.account"
                :placeholder="$t('login.username')"
                name="account"
                type="text"
                tabindex="1"
                autocomplete="on"
                prefix-icon="el-icon-user"
                size="large"
                @change="getConfig"
              ></el-input>
            </el-form-item>
            <!-- <el-form-item class="rule-tip">{{ $t("login.rule") }}</el-form-item> -->
            <el-tooltip
              v-model="capsTooltip"
              :content="$t('login.upper')"
              placement="right"
              manual
            >
              <el-form-item prop="password" style="margin-bottom: 26px">
                <el-input
                  ref="password"
                  v-model="loginForm.password"
                  show-password
                  :placeholder="$t('login.password')"
                  name="password"
                  tabindex="2"
                  autocomplete="on"
                  @keyup.native="checkCapslock"
                  @blur="capsTooltip = false"
                  prefix-icon="el-icon-lock"
                  size="large"
                ></el-input>
                <!-- @keyup.enter.native="handleLogin" -->
              </el-form-item>
            </el-tooltip>
            <el-form-item prop="code" v-if="needCode">
              <el-row type="flex" justify="space-between">
                <el-col class="sms-input">
                  <el-input
                    v-model="loginForm.code"
                    :placeholder="$t('login.codeTip')"
                    name="code"
                    autocomplete="on"
                    prefix-icon="el-icon-key"
                    size="large"
                  >
                  </el-input>
                </el-col>
                <el-col class="sms-right code-right">
                  <el-tooltip
                    :content="$t('login.changeCode')"
                    placement="bottom"
                  >
                    <img
                      id="imgcode"
                      :alt="$t('login.changeCode')"
                      :src="define.comUrl + imgUrl"
                      @click="changeImg"
                    />
                  </el-tooltip>
                </el-col>
              </el-row>
            </el-form-item>
            <el-button
              :loading="loading"
              type="primary"
              class="login-btn"
              size="large"
              @click.native.prevent="handleLogin"
              >{{ $t("login.logIn") }}
            </el-button>
          </el-form>
          <div v-show="active == 2" class="login-form-QRCode">
            <!-- <img class="qrcode-img" src="@/assets/images/login_qr.png"> -->
            <span id="qr_login" />
            <!--  <p class="qrcode-tip">正在测试,稍后上线</p> -->
          </div>
        </div>
      </div>
      <!--<div class="login-foot">Copyright 引迈信息技术有限公司, All Rights Reserved. 沪ICP备17044791号-1
      助力企业和团队快速实现目标</div>-->
    </div>
    <div class="copyright">
      <p>©版权所有 科技股份有限公司</p>
    </div>
  </div>
</template>

<script>
import { getConfig } from "@/api/user";
import { REDIRECT_URI } from "@/constant";
import "@/utils/rem.js";

import { resetRouter } from "@/router";
export default {
  name: "Login",
  data() {
    return {
      ifScanCode: 0,
      loginForm: {
        account: "",
        password: "",
        code: "",
        origin: "password",
      },
      loginRules: {
        account: [
          {
            required: true,
            trigger: "blur",
            message: this.$t("login.accountTip"),
          },
        ],
        password: [
          {
            required: true,
            trigger: "blur",
            message: this.$t("login.passwordTip"),
          },
        ],
        code: [
          {
            required: true,
            trigger: "blur",
            message: this.$t("login.codeTip"),
          },
        ],
      },
      imgUrl: "",
      timestamp: "",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      needCode: false,
      codeLength: 4,
      redirect: undefined,
      showTxt: false,
      otherQuery: {},
      active: 1,
      ComputerUrl: "http://gl.bringspring.com/jsbos-web/#/login",
      pathTitle: "",
    };
  },
  computed: {
    sysConfig() {
      return this.$store.state.settings.sysConfig;
    },
    loginLoading() {
      return this.$store.state.user.loginLoading;
    },
  },
  watch: {
    "$route.query": {
      handler(newVal, oldVal) {
        var code = this.$route.query["code"];
        if (code) {
          this.qywxLoginByCode(code);
        }
        // this.getRoutes();
      },
    },

    loginLoading(val) {
      if (!val) this.loading = false;
    },
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  created() {
    // this.getRoutes();  //公司text
    console.log("this.$route.query", this.$route.query);
    // 判断是否微信浏览器打开

    var ua = navigator.userAgent.toLowerCase();
    var isWeixin = ua.indexOf("micromessenger") !== -1;
    if (isWeixin) {
      const code = this.getUrlParam("code");
      if (code) {
        this.qywxLoginByCode(code);
      } else {
        this.getCode();
      }
    }
    const _this = this;
    document.onkeydown = function (e) {
      const { keyCode } = e;
      if (keyCode === 13) {
        _this.handleLogin();
      }
    };
    if (this.needCode) this.changeImg();
  },
  mounted() {
    this.$store.commit("user/SET_LOGIN_LOADING", false);
    this.setShowTxt();
    window.onresize = () => {
      this.setShowTxt();
    };
  },
  destroyed() {
    document.onkeydown = function (e) {
      const { keyCode } = e;
      if (keyCode === 13) {
      }
    };
  },
  methods: {
    // 判断浏览器地址,根据地址展示不同信息
    // getRoutes() {
    //   switch (this.$route.path) {
    //     case "/contract-login":
    //       // 神州视翰
    //       this.pathTitle = "";
    //       break;
    //     case "/-login":
    //       // 科技
    //       this.pathTitle = "";
    //       break;
    //     case "/shmj-login":
    //       // 上海米健
    //       this.pathTitle = "";
    //       break;
    //     default:
    //       this.pathTitle = "";
    //   }
    // },
    setShowTxt() {
      if (document.documentElement.clientHeight <= 840) {
        this.showTxt = false;
      } else {
        this.showTxt = true;
      }
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    getConfig(val) {
      if (!val) return;
      getConfig(this.loginForm.account).then((res) => {
        this.needCode = !!res.data.enableVerificationCode;
        if (this.needCode) {
          this.codeLength = res.data.verificationCodeNumber || 4;
          this.changeImg();
        }
      });
    },
    async handleLogin() {
      if (this.loading) return;
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store.commit("user/SET_LOGIN_LOADING", true);
          const query = {
            ...this.loginForm,
            timestamp: this.timestamp,
          };
          this.$store
            .dispatch("user/login", query)
            .then((res) => {
              this.$store.dispatch("tagsView/closeAll");
              //重新获取系统菜单
              let contractId = "454556140475292421";
              this.$store
                .dispatch("user/getInfo", "454556140475292421")
                .then(async (rese) => {
                  resetRouter();
                  const accessRoutes = await this.$store.dispatch(
                    "permission/generateRoutes",
                    rese
                  );
                  this.$router.addRoutes(accessRoutes);
                  // console.log("滴滴滴滴", contractId);
                  this.$router.push({
                    // 首页home   调整到客户资源界面默认
                    // path: this.redirect || "/basic/contract_portal",
                    path: this.redirect || "/dashboard",
                    query: {
                      applicationId: contractId,
                      // otherQuery: this.otherQuery,
                    },
                  });
                });
            })
            .catch(() => {
              this.$store.commit("user/SET_LOGIN_LOADING", false);
            });
        } else {
          return false;
        }
      });
    },
    handleLoginTest(code) {
      this.loading = true;
      this.$store.commit("user/SET_LOGIN_LOADING", true);
      this.$store
        .dispatch("user/loginByWeCom", code)
        .then((res) => {
          this.$router.push({
            // 首页home   调整到客户资源界面默认
            // path: this.redirect || "/contract_portal",
            path: this.redirect || "/dashboard",
            // query: this.otherQuery,
          });
        })
        .catch(() => {
          this.$store.commit("user/SET_LOGIN_LOADING", false);
        });
    },
    changeImg() {
      let timestamp = Math.random();
      this.timestamp = timestamp;
      this.imgUrl = `/api/oauth/ImageCode/${this.codeLength || 4}/${timestamp}`;
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    qywxLoginByCode(code) {
      this.loading = true;
      this.$store.commit("user/SET_LOGIN_LOADING", true);
      this.$store
        .dispatch("user/loginByWeCom", code)
        .then((res) => {
          this.$router.push({
            // 首页home   调整到客户资源界面默认
            // path: this.redirect || "/contract_portal",
            path: this.redirect || "/dashboard",
            // query: this.otherQuery,
          });
        })
        .catch(() => {
          this.$store.commit("user/SET_LOGIN_LOADING", false);
        });
    },
    getCode() {
      // 获取路径URL

      // 企业微信跳转路径
      let REDIRECT_URI = encodeURIComponent(this.ComputerUrl);
      window.location.replace(
        `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwc0366cea7d993696&redirect_uri=${REDIRECT_URI}&response_type=code&scope=snsapi_base&state=STATE&agentid=1000034#wechat_redirect`
      );
    }, //获取地址栏url后的参数值
    getUrlParam(key) {
      var href = window.location.href;
      var url = href.split("?");
      if (url.length <= 1) {
        return "";
      }
      var params = url[1].split("&");

      for (var i = 0; i < params.length; i++) {
        var param = params[i].split("=");
        if (key == param[0]) {
          return param[1];
        }
      }
    },
    loadWeComQrImage() {
      var wwLogin = new WwLogin({
        id: "qr_login",
        appid: "wwc0366cea7d993696",
        agentid: "1000034",
        redirect_uri: encodeURIComponent(REDIRECT_URI),
        state: "hellowecom",
        href: "",
        lang: "zh",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../szsh.scss";
</style>
